import { applyMiddleware, createStore, compose } from 'redux';
import AES from 'crypto-js/aes';
import encUtf8 from 'crypto-js/enc-utf8';
import { saveLocalStorageMiddleware, loadLocalStorage, removeLocalStorage } from '../../src';
import reducers from './reducer';

/**
 * localStorage储存
 */
const capacityNamespace = 'ox'; // 扩容的命名空间
const capacityDomain = 'http://capacity-ox-spns.duanshenghua.cn'; // 扩容域名
const capacityIframeId = 'ox-redux-cache'; // 扩容iframe id
const encKey = 'secret key 123'; // enc加密key

// 储存中间件
const localStorageMiddleware = saveLocalStorageMiddleware({
  namespace: capacityNamespace,
  shake: 1000,
  iframeId: capacityIframeId,
  iframeSrc: capacityDomain,
  dataDispose: data => AES.encrypt(data, encKey).toString(),
  // onSuccess(data) {
  //   console.log('localStorageMiddleware设置成功：', data);
  // },
  onError(err) {
    console.log('localStorageMiddleware设置失败：', err);
  },
});
// 初始化时获取默认值
const initDataResolve = loadLocalStorage({
  namespace: capacityNamespace,
  iframeId: capacityIframeId,
  iframeSrc: capacityDomain,
  dataDispose: data => AES.decrypt(data, encKey).toString(encUtf8),
});
// 删除存储的值
function removeRedux(): Promise<void> {
  return removeLocalStorage({
    namespace: capacityNamespace,
    iframeSrc: capacityDomain,
    iframeId: capacityIframeId,
  });
}

const middleware = applyMiddleware(localStorageMiddleware);
const enhancer = compose(middleware);

// 获取仓库
function getStore(): Promise<any> {
  return new Promise((resolve) => {
    initDataResolve
      .then(data => {
        resolve(createStore(
          reducers,
          data,
          enhancer,
        ));
      })
      .catch(() => {
        resolve(createStore(
          reducers,
          undefined,
          enhancer,
        ));
      });
  });
}

export {
  removeRedux,
};

export default getStore;
